package q19

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	var m = []*ListNode{}
	for head != nil {
		m = append(m, head)
		head = head.Next
	}
	l := len(m)

	lastIndex := l - 1
	preIndex := l - n - 1
	nextIndex := l - n + 1
	if preIndex < 0 && nextIndex > lastIndex {
		return nil
	} else if preIndex < 0 {
		return m[1]
	} else if nextIndex > lastIndex {
		m[preIndex].Next = nil
	} else {
		m[preIndex].Next = m[nextIndex]
	}
	return m[0]
}
